<template>
  <div>
    <!-- 查询参数及按钮部分 -->

    <el-dialog  v-dialogDrag  
      :title="dialogStatus"
      :visible.sync="dialogEditFormVisible"
      style="padding:0px"
      width="50%"
    >
      <el-form
        ref="dataForm"
        class="dialog-Backgroundcolor"
        :model="formData"
        label-position="right"
        label-width="100px"
      >
        <el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="变动单位:">
                <el-select
                  v-model="listQuery.bddw"
                  class="filter-item borderwidth"
                  clearable
                  placeholder="--请选择--"
                >
                  <el-option
                    v-for="item in bddws"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="人员类型:">
                <el-select
                  v-model="listQuery.rylx"
                  class="filter-item borderwidth"

                  placeholder="--请选择--"
                >
                  <el-option
                    v-for="item in rylxs"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top:8px">
            <el-col :span="12">
              <el-form-item label="工资类型:">
                <el-select
                  v-model="listQuery.gzlx"
                  class="filter-item borderwidth"
                  clearable
                  placeholder="--请选择--"
                >
                  <el-option
                    v-for="item in gzlxs"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="单位名称:">
                <el-input
                  v-model="listQuery.dwmc"
                  class="filter-item borderwidth"
                />
              </el-form-item>
            </el-col>

          </el-row>
          <el-button
            type="primary"
            style="float:right;margin-top:10px"
            @click="query"
          >
            查询
          </el-button>
        </el-row>
      </el-form>
    </el-dialog>
    <el-row>

      <el-col :span="12">

        <el-select
          v-model="listQuery.rylx"
          class="filter-item"
          placeholder="--请选择--"
          @change="handleFilter"
        >
          <el-option
            label="全部人员"
            value=""
          />
          <el-option
            label="在职人员"
            value="3"
          />
          <el-option
            label="离退休人员"
            value="1"
          />
        </el-select>

      </el-col>
    </el-row>
    <!-- 表格部分 -->
    <el-table
      ref="singalTable"
      v-loading="listLoading"
      :data="list"
      :stripe="true"
      fit
      :height="tableHeight"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      :summary-method="getSummaries"
      show-summary
      @selection-change="handleSelectionChange"
    >
      <template slot="empty">
        <tableEmpty />
      </template>
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        label="序号"
        prop="index"
        align="center"
        width="80"
      />
      <el-table-column
        label="工资月份"
        align="center"
        width="110"
      >
        <template slot-scope="{row}">
          <span>{{ row.month }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="单位编码"
        align="center"
        width="110"
      >
        <template slot-scope="{row}">
          <span style="float: left">{{ row.agencyCode }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="单位名称"
        align="center"
      >
        <template slot-scope="{row}">
          <span style="float: left">{{ row.agencyName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="实发工资总额"
        align="center"
        prop="sfgzze"
      >
        <template slot-scope="{row}">
          <span style="float: right">{{ Number(row.sfgzze).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="应发工资总额"
        align="center"
        prop="yfgzze"
      >
        <template slot-scope="{row}">
          <span style="float: right">{{ Number(row.yfgzze).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        align="center"
      >
        <template slot-scope="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页   -->
    <pagination
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 单位上报情况查询 -->
    <el-dialog  v-dialogDrag  
      title="单位上报情况"
      :visible.sync="unitReportVisible"
      style="padding:0px"
      width="70%"
    >
      <el-button size="small" type="primary" @click="get_persontest_list">人员检测</el-button>
      <el-button size="small" type="primary" @click="getPersontestList">调出未调入检测</el-button>
      <el-tabs
        v-model="unitReportState"
        class="dialog-Backgroundcolor"
      >
        <el-tab-pane
          label="已上报"
          style="margin-left:4%"
          name="isReport"
        >
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="是否自动上报">
              <el-select v-model="formInline.is_auto" placeholder="查询区域" @change="is_auto_change">
                <el-option label="" value="" />
                <el-option label="是" value="1" />
                <el-option label="是（有变动）" value="2" />
                <el-option label="否" value="0" />
              </el-select>
            </el-form-item>
          </el-form>
          <el-table
            ref="unitReportTable"
            v-loading="unitReportListLoading"
            :data="unitReportList"
            :stripe="true"
            fit
            height="455px"
            max-height="455px"
            :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          >
            <template slot="empty">
              <tableEmpty />
            </template>
            <el-table-column
              type="index"
              width="50"
              label="序号"
            />
            <el-table-column
              label="上报状态"
              align="center"
            >
              <template slot-scope="{row}">
                <span>{{ row.isSalarySubmit | isSalarySubmitFilter }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="单位名称"
              align="center"
            >
              <template slot-scope="{row}">
                <span style="float: left">{{ row.agencyName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="单位编码"
              align="center"
            >
              <template slot-scope="{row}">
                <span style="float: left">{{ row.agencyCode }}</span>
              </template>
            </el-table-column>

            <el-table-column
              label="上报时间"
              align="center"
            >
              <template slot-scope="{row}">
                <span>{{ row.updateTime | parseTime }}</span>
              </template>
            </el-table-column>
            <el-table-column label="是否自动上报" align="center">
              <template slot-scope="{row}">
                <span>{{ row.is_auto | isAutoSubmitFilter }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            :total="unitReportTotal"
            :page.sync="unitReportListQuery.page"
            :limit.sync="unitReportListQuery.limit"
            @pagination="getUnitReportList"
          />
        </el-tab-pane>
        <el-tab-pane
          label="未上报"
          style="margin-left:4%"
          name="noReport"
        >
        <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px;"
            type="primary"
            :loading="autoSubmitLoading"
            @click="autoSubmit"
          >
            自动上报
          </el-button>
          <el-table
            ref="unitReportTable"
            v-loading="unitReportListLoading"
            :data="unitReportList"
            :stripe="true"
            fit
            height="455px"
            max-height="455px"
            :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          >
            <template slot="empty">
              <tableEmpty />
            </template>
             <el-table-column type="selection" width="30" align="center" />
            <el-table-column
              type="index"
              width="50"
              label="序号"
            />
            <el-table-column
              label="上报状态"
              align="center"
            >
              <template slot-scope="{row}">
                <span>{{ row.isSalarySubmit | isSalarySubmitFilter }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column
              label="最后操作日期"
              align="center"
            >
              <template slot-scope="{row}">
                <span>{{ row.updateTime | parseTime }}</span>
              </template>
            </el-table-column> -->
            <el-table-column
              label="单位编码"
              align="center"
            >
              <template slot-scope="{row}">
                <span style="float: left">{{ row.agencyCode }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="单位名称"
              align="center"
            >
              <template slot-scope="{row}">
                <span style="float: left">{{ row.agencyName }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            :total="unitReportTotal"
            :page.sync="unitReportListQuery.page"
            :limit.sync="unitReportListQuery.limit"
            @pagination="getUnitReportList"
          />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog  v-dialogDrag  
      title="审核说明"
      :visible.sync="auditFormVisible"
      width="30%"
      max-height="500px"
    >
      <el-form
        ref="auditForm"
        :model="formData"
        label-position="right"
        label-width="120px"
        size="small"
      >
        <el-row>
          <el-col>
            <el-input
              v-model="formData.auditExplain"
              type="textarea"
              :rows="4"
              maxlength="500"
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col
            :span="16"
            style="text-align: right; margin-top:5%"
          >
            <el-button
              type="primary"
              :loading="saveExplainLoading"
              @click="saveExplain"
            >
              确定
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <!--审核日志 -->
    <ApprovalProcess ref="app" />
    <persontest v-if="ifShow" :list="persontest_list" @close="ifShow = false" />
    <personTransfer  v-if="ifShow2" :list="personTransfer" @close="ifShow2 = false" />

  </div>
</template>
<script>
import {
  getSalaryList,
  confirmSalary,
  undoConfirmSalary,
  sendBackSalary,
  queryUnitReportPage,
  get_persontest_list,
  autoSubmit,
  getpersonTransferList
} from '@/api/salaryReport/financialVerify'
// 分页
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import tableEmpty from '@/components/table/empty'
import ApprovalProcess from '@/components/ApprovalProcess/ApprovalProcess'
import persontest from './persontest'
import personTransfer from './personTransfer'


export default {
  name: 'Unit',
  components: { ApprovalProcess, Pagination, tableEmpty, persontest, personTransfer },
  filters: {
    isMonthEndFilter(type) {
      if (type === '0') {
        return '未月结'
      } else if (type === '1') {
        return '已月结'
      }
    },
    isSalarySubmitFilter(state) {
      if (state === '0') {
        return '未上报'
      } else if (state === '-1') {
        return '被退回'
      } else if (state === '-9') {
        return '未上报'
      } else if (state === '1') {
        return '已上报'
      }
    },
    isAutoSubmitFilter(state) {
      if (state === '0') {
        return '否'
      }
      if (state === '1') {
        return '是'
      }
      if (state === '2') {
        return '是（有变动）'
      }
    }
  },
  props: ['tabPane'],
  data() {
    return {
      ifShow: false,
      ifShow2: false,
      persontest_list: [],
      personTransfer: [],
      formInline: {
        is_auto: ''
      },
      tableHeight: null,
      unitReportVisible: false,
      unitReportVisibles: false,
      unitReportState: 'isReport',
      unitReportListLoading: false,
      autoSubmitLoading: false,
      unitReportList: [],
      unitReportTotal: 0,
      unitReportListQuery: {
        page: 1,
        limit: 200
      },
      dialogStatus: '',
      dialogEditFormVisible: false,
      that: this,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 500,
        title: undefined,
        flag: 'noAudit',
        agencyId: '0',
        month: new Date(),
        bddw: '',
        rylx: '',
        gzlx: '',
        dwmc: '',
        menuid: this.$router.currentRoute.meta.menuid
      },
      formData: {
        id: '',
        agencyCode: '',
        agencyName: '',
        sfgzze: '',
        yfgzze: '',
        remark: '',
        auditExplain: '' // 审核说明
      },
      months: [
        { code: '1', name: '一月份' },
        { code: '2', name: '二月份' },
        { code: '3', name: '三月份' }
      ],
      bddws: [{ code: '1', name: '有变动' }, { code: '0', name: '无变动' }],
      rylxs: [{ code: '', name: '全部人员' }, { code: '3', name: '在职人员' }, { code: '1', name: '离退休人员' }],
      gzlxs: [
        { code: '1', name: '事业人员' },
        { code: '0', name: '行政人员' },
        { code: '11', name: '离退休人员' }
      ],
      salarys: [],
      title1: '',
      saveExplainLoading: false,
      auditFormVisible: false,
      operateAgencyIds: [], // 操作单位id集合
      tmp_unitReportList: [],
      selected_list: []
    }
  },
  watch: {
    unitReportState() {
      this.getUnitReportList()
    },
    // 表格的数据数组
    list(val) {
      this.doLayout()
    }
  },
  mounted() {
    this.getTbHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  // 加载后运行
  created() {
    // 获取参数
    this.listQuery.flag = this.tabPane
    // 加载获取全部数据
    this.getList()
  },
  methods: {
    get_persontest_list() {
      get_persontest_list().then((res) => {
        if (res && res.data && res.data.length > 0) {
          this.persontest_list = res.data
          this.ifShow = true
        } else {
          this.$message({
            showClose: true,
            message: res.result,
            type: 'success',
            duration: 2000
          })  
        }
      })
    },
    getPersontestList(){
    getpersonTransferList().then((res) => {
        if (res && res.data && res.data.length > 0) {
           this.personTransfer = res.data
           this.ifShow2 = true
        } else {
          this.$message({
            showClose: true,
            message: res.result,
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    autoSubmit(){
      const selection =  this.$refs.unitReportTable.selection
      if (selection.length === 0) {
        this.$message({
          message: '请选择要自动上报的单位',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        return
      }
      this.autoSubmitLoading=true
      let agencyids=[]
      selection.forEach(item => {
        agencyids.push(item.agencyId)
      })
      const data = {}
      data['agencyIds'] =agencyids

      autoSubmit(data).then((res) => {
          this.$message({
            showClose: true,
            message: res.result,
            type: 'success',
            duration: 2000
          })
          this.unitReportVisible = false
      this.unitReportListLoading = false
          this.autoSubmitLoading=false
           this.getList()
      }).catch((res)=>{
           this.unitReportVisible = false
          this.unitReportListLoading = false
          this.autoSubmitLoading=false
           this.getList()
      })
    },
    // 已上报页签，列表筛选
    is_auto_change() {
      this.getUnitReportList()
    },
    // 退回
    auditReject() {
      this.operateAgencyIds = []
      const selection = this.$refs.singalTable.selection
      if (selection.length === 0) {
        this.$message({
          message: '请选择要退回的单位',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        return
      }
      selection.forEach(item => {
        this.operateAgencyIds.push(item.id)
      })
      this.operateCode = 'reject'
      this.formData = Object.assign({}, this.formData, '')
      if (selection.length === 1) {
        const auditExplain = selection[0].auditExplain
        this.formData.auditExplain = auditExplain === null ? '不同意' : auditExplain.substring(auditExplain.indexOf('：') + 1)
      } else {
        this.formData.auditExplain = '不同意'
      }
      this.title1 = '退回说明'
      this.auditFormVisible = true
    },
    // 统一保存
    saveExplain() {
      this.saveExplainLoading = true
      this.sendBack()
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 260
    },
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    handleEdit() {
      this.dialogStatus = '单位基本信息'
      this.dialogEditFormVisible = true
      this.formData = Object.assign({}, this.formData)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 审核日志
    processnode() {
      const selection = this.$refs.singalTable.selection
      if (selection.length !== 1 || selection.length == 0) {
        this.$message({
          showClose: true,
          message: '请选择一条数据',
          type: 'warning',
          duration: 4000
        })
        return
      }
      if (!selection[0].id) {
        selection.splice(0, 1)
      }
      this.$refs.app.getList(selection[0].id)
    },
    getList() {
      this.listLoading = true
      getSalaryList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
      })
    },

    // 更新
    handleFilter() {
      this.getList()
    },
    // 确认
    handleConfirm() {
      const selection = this.$refs.singalTable.selection
      if (selection.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择数据',
          type: 'warning',
          duration: 4000
        })
        this.$emit('handleCallback')
        return
      }
      // 清空数组
      this.salarys.splice(0, this.salarys.length)

      // 提示框确认
      // this.$confirm('确定吗？', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      selection.forEach(item => {
        this.salarys.push(item.id)
      })
      const data = {}
      data['agencyIds'] = this.salarys
      data['menuid'] = this.$router.currentRoute.meta.menuid
      data['menuname'] = this.$router.currentRoute.meta.menuname
      confirmSalary(data).then(response => {
        this.dialogFormVisible = false
        this.$message({
          showClose: true,
          message: '接收成功',
          type: 'success',
          duration: 4000
        })
        this.$emit('handleCallback')
        // 更新
        this.handleFilter()
      })
      // })
      // .catch(() => {
      //   this.$emit('handleCallback')
      // })
    },
    // 树方法
    handleTree(data) {
      // if (!Object.prototype.hasOwnProperty.call(data, 'children')) {
      this.listQuery.agencyId = data.id
      this.getList()
      // }
    },
    // 撤销
    undoConfirm() {
      // 清空数组
      this.salarys.splice(0, this.salarys.length)
      const selection = this.$refs.singalTable.selection
      if (selection.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择数据',
          type: 'warning',
          duration: 4000
        })
        this.$emit('ConfirmCallBack')
        return
      }
      // 循环检查数据
      let state = true
      for (let index = 0; index < selection.length; index++) {
        const element = selection[index]
        if (element.isMonthEnd === '1') {
          state = false
          this.$message({
            showClose: true,
            message: '已月结的数据不能退回',
            type: 'warning',
            duration: 4000
          })
          this.$emit('ConfirmCallBack')
          break
        }
      }
      if (state) {
        // 提示框确认
        // this.$confirm('确定吗撤销吗？', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // })
        //   .then(() => {
        selection.forEach(item => {
          this.salarys.push(item.id)
        })
        const data = {}
        data['agencyIds'] = this.salarys
        data['menuid'] = this.$router.currentRoute.meta.menuid
        data['menuname'] = this.$router.currentRoute.meta.menuname
        undoConfirmSalary(data).then(response => {
          this.dialogFormVisible = false
          this.$message({
            showClose: true,
            message: '撤销成功',
            type: 'success',
            duration: 4000
          })
          this.$emit('ConfirmCallBack')
          // 更新
          this.handleFilter()
          // })
        })
          .catch(() => {
            this.$emit('ConfirmCallBack')
          })
      }
    },
    // 查询
    Query() {
      this.dialogStatus = '查询'
      this.dialogEditFormVisible = true
    },
    // 查询
    query() {
      this.dialogEditFormVisible = false
      this.handleFilter()
    },
    // 退回
    sendBack() {
      // 清空数组
      this.salarys.splice(0, this.salarys.length)
      const selection = this.$refs.singalTable.selection
      if (selection.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择数据',
          type: 'warning',
          duration: 4000
        })
        this.$emit('BackCallBack')
        return
      }
      // 清空数组
      this.salarys.splice(0, this.salarys.length)
      // 提示框确认
      // this.$confirm('确定退回吗？', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      selection.forEach(item => {
        this.salarys.push(item.id)
      })
      const data = {}
      data['agencyIds'] = this.salarys
      data['menuid'] = this.$router.currentRoute.meta.menuid
      data['menuname'] = this.$router.currentRoute.meta.menuname
      data['params'] = this.$route.meta.pageUrl
      data['auditExplain'] = this.formData.auditExplain
      sendBackSalary(data).then(response => {
        this.dialogFormVisible = false
        this.$message({
          showClose: true,
          message: '退回成功',
          type: 'success',
          duration: 4000
        })
        this.auditFormVisible = false
        this.saveExplainLoading = false
        this.$emit('BackCallBack')
        // 更新
        this.handleFilter()
        // })
      })
        .catch(() => {
          this.$emit('BackCallBack')
        })
    },
    // 单位上报情况查询
    unitReportQuery() {
      this.unitReportVisible = true
      this.unitReportListLoading = true
      this.handleUnitReportFilter()
    },

    handleUnitReportFilter() {
      this.unitReportListQuery.page = 1
      this.unitReportListQuery.limit = 200
      this.getUnitReportList()
    },

    getUnitReportList() {
      this.unitReportListLoading = true
      this.unitReportList = []
      this.unitReportListQuery.state = this.unitReportState
      this.unitReportListQuery.is_auto = this.formInline.is_auto
      queryUnitReportPage(this.unitReportListQuery).then(res => {
        this.unitReportList = res.data.rows
        this.tmp_unitReportList = JSON.parse(JSON.stringify(this.unitReportList))
        this.unitReportTotal = res.data.total
        this.unitReportListLoading = false
      }).catch(() => {
        this.unitReportList = []
        this.unitReportTotal = 0
        this.unitReportListLoading = false
      })
    },
     // 获取勾选的数据data
    handleSelectionChange(val) {
        this.selected_list = val;
      
      },
    //自定义合计
    getSummaries(param) {    
        const { columns, data } = param;      
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计';
            return;
          }
          if (index <5) {
            return;
          }
          let values;
          values = data.map(item => Number(item[column.property])); // 无勾选
          if (this.selected_list && this.selected_list.length > 0) { // 有勾选
          values = this.selected_list.map(item => Number(item[column.property]));
            }
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            if(index>=5){
              sums[index]= Number(sums[index]).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
              sums[index] += ' 元';
            }
          } else {
            sums[index] = '';
          }
        });
    
        return sums;
      }
  }
}
</script>
<style scoped lang="scss">
@import "~@/styles/border.scss"; /*引入公共样式*/
// ::v-deep tbody > tr:nth-child(1) {
//   .el-checkbox {
//     display: none;
//   }
// }
</style>
